package com.campfire.intelligentsecurity.config;

import com.campfire.intelligentsecurity.sys.kit.AESUtil;
import com.github.drinkjava2.jsqlbox.DbContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;

import javax.sql.DataSource;

@Configuration
@Order(1)
public class DataSourceConfig {
    @Autowired
    @Qualifier("mainDs")
    public DataSource mainDs;

    @Bean(name = "mainDbProp")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.main")
    public DataSourceProperties mainProp() {
        return new DataSourceProperties();
    }

    @Primary
    @Bean(name = "mainDs")
    public DataSource mainDs(@Qualifier("mainDbProp") DataSourceProperties dataSourceProperties) {
        try {
            dataSourceProperties.setPassword(AESUtil.decode(dataSourceProperties.getPassword()));
            return dataSourceProperties.initializeDataSourceBuilder().build();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Bean(name = "main")
    public DbContext mainDbContext() {
        DbContext ctx = new DbContext(mainDs);
        DbContext.setGlobalDbContext(ctx);
        ctx.setAllowShowSQL(true);
        return ctx;
    }
}
